package cn.marinda.runnable;

import cn.marinda.MinecraftServerHelper;
import cn.marinda.config.PropertiesServerConfig;
import cn.marinda.entity.ServerInfo;
import cn.marinda.factory.ServerConfigFactory;
import cn.marinda.gui.impl.DownloadServerDiaLogImpl;
import cn.marinda.gui.impl.SuccessCreateServerDialogImpl;
import cn.marinda.util.ServerUtils;
import cn.marinda.util.SwingUtils;
import cn.marinda.util.ThreadUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

/**
 * 服务器注入配置任务
 *
 * @author admin
 * @date 2022/07/26
 */
public class ServerImmitConfigRunnable implements Runnable{

    private Map<String, Boolean> selectPropertiesMap = new HashMap<>();
    private Map<String, String> settingPropertiesMap = new HashMap<>();
    private ServerInfo serverInfo;

    /**
     * 服务器引入配置可运行
     *
     * @param selectPropertiesMap  选择属性映射
     * @param settingPropertiesMap 设置属性映射
     */
    public ServerImmitConfigRunnable(Map<String, Boolean> selectPropertiesMap, Map<String, String> settingPropertiesMap, ServerInfo serverInfo) {
        this.selectPropertiesMap = selectPropertiesMap;
        this.settingPropertiesMap = settingPropertiesMap;
        this.serverInfo = serverInfo;
    }

    @Override
    public void run() {
        if(validCoreDownloadFlag() && serverInfo.getServerProperties() != null){
//            注入
            immitServerProperties();
            if(ServerUtils.writeServerPropertiesFlag){
                openSuccessDialog();
                //        彻底返写后关闭线程
                ThreadUtils.serverImmitScheduledFuture.cancel(true);
            }
        }
    }

    private void openSuccessDialog(){
        SwingUtils.downloadDialog.close();
        SwingUtils.createSuccessDialgo = SuccessCreateServerDialogImpl.instace;
        SwingUtils.createSuccessDialgo.open();
    }

    /**
     * 验证核心下载是否结束
     *
     * @return boolean
     */
    private boolean validCoreDownloadFlag() {
        if (ThreadUtils.downloadScheduled != null) {
            if (ThreadUtils.downloadScheduled.isCancelled()) {
                return true;
            }
        }
        return false;
    }

    /**
     * 有效注入属性文件
     *
     * @return boolean
     */
    private boolean validImmitPropertiesFile() {
        return serverInfo.getEulaFile().exists() && serverInfo.getServerProperties().exists();
    }


    /**
     * 注入服务器文件
     */
    private void immitServerProperties() {
        try {
            PropertiesServerConfig propertiesServerConfig = (PropertiesServerConfig) ServerConfigFactory.getServerConfigurationByName("properties");
            propertiesServerConfig.bindSelectPropertiesMap(selectPropertiesMap);
            propertiesServerConfig.bindSettingPropertiesMap(settingPropertiesMap);
            propertiesServerConfig.immitConfig();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
